import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import {Image, Swiper, SwiperItem, View, Button} from '@tarojs/components'
import { SDBody, SDQuantity } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout, setShopCart } from '../../../redux/actions'

import Graphics from '../../../comps/graphics'
import Comment from '../../../comps/comment'
import SDButton from '../../../comps/sd-button'

import SilverPriceIcon from '../../../images/ic_money.png'
import PlayIcon from '../../../images/ic_play.png'
import CartIcon from '../../../images/ic_shopping_cart_small.png'
import CollectPreIcon from '../../../images/ic_collection_small_pre.png'
import CollectNorIcon from '../../../images/ic_collection_small_nor.png'
import ServiceIcon from '../../../images/ic_service.png'


import './index.less'


type PageState = {
  mainIsLoading: boolean,
  bannerIndex: number,
  tabBarIndex: number,
  skuList: any[],
  silverPriceData: any,
  productData: any,
  totalCount: number,
  totalPrice: number,
  btnIsLoading: boolean,
  cartCount: number
}

type PageOwnProps = {}

interface GoodsDetailPage {
  props: PageProps & PageOwnProps
}


@connect(({userState, cartState}) => ({
  userState,
  cartState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  },
  setShopCart(cartData) {
    dispatch(setShopCart(cartData))
  }
}))
class GoodsDetailPage extends Component<PageOwnProps, PageState> {

  constructor (args) {
    super(args)
    this.state = {
      mainIsLoading: true,
      bannerIndex: -1,
      tabBarIndex: 0,
      skuList: [],
      silverPriceData: {},
      productData: {},
      totalCount: 0,
      totalPrice: 0,
      btnIsLoading: false,
      cartCount: 0
    }
  }

  config: Config = {
    navigationBarTitleText: '商品详情'
  }

  componentDidMount () {
    let productId = (this.$router.params || {}).productId || '1'
    this.fetchData(productId)
  }

  render () {
    const bottomSafeHeight = Taro.getSystemInfoSync().statusBarHeight == 44 ? 34 : 0;
    const {
      mainIsLoading,
      bannerIndex,
      skuList,
      tabBarIndex,
      silverPriceData,
      productData,
      totalPrice,
      totalCount,
      btnIsLoading,
      cartCount
    } = this.state
    const { userState: {isLogin} } = this.props
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className='main-banner'>
          <Swiper className='banner-swiper' indicatorDots={false} circular autoplay duration={300} onChange={this.onSwiperChange}>
            {
              productData.productMedias.map((item, index) => {
                return <SwiperItem className='banner-swiper-item' key={index}>
                  <Image src={item.mediaUrl} mode='aspectFill' lazyLoad className='banner-img' onClick={this.previewImage.bind(this, item.mediaUrl)} />
                    {
                      item.type == 'VIDEO' ? <View className='inner' onClick={this.gotoVideoPlayer}>
                        <Image src={PlayIcon} className='play-icon'/>
                      </View> : null
                    }
                </SwiperItem>
              })
            }
          </Swiper>
          <View className='banner-dots'>
            {
              productData.productMedias.map((_, index) => {
                return <View key={index} className={index == bannerIndex ? `dot-item dot-item_current` : `dot-item`}></View>
              })
            }
          </View>
        </View>

        {/** 今日银价 */}
        <View className='banner-tips'>
          <Image src={SilverPriceIcon} className='icon' />
          <View className='title'>今日银价:{SDUtils.formatPrice(`${silverPriceData.price}`, false)}/g</View>
        </View>

        {/** 商品基本信息 */}
        <View className='section base-section'>
          <View className='title'>{productData.name}</View>
          <View className='item center'>
            <View className='left'>
              <View className='left-item'>{productData.priceRange}</View>
              {/*<View className='left-item'>工费: ¥8.00/g</View>*/}
            </View>
            <View className='right'>收藏：320</View>
          </View>
          <View className='item'>
            <View className='left'>
              {/*<View className='left-item'>吊牌价：¥198.00</View>*/}
              <View className='left-item'>工费：{SDUtils.formatPrice(productData.processFee || 0)}/g</View>
            </View>
            <View className='right'>销量：320</View>
          </View>
          <View className='tag-content'>
            <View className='tag-title'>标签</View>
            <View className='tag-list'>
              {
                productData.tagsList.map((item, index) => {
                  return (
                    <View className='tag-item' key={index}>{item}</View>
                  )
                })
              }
            </View>
          </View>
        </View>

        {/** 成交信息 */}
        <View className='section trade-section'>
          <View className='title'>我的成交</View>
          <View className='bottom'>
            <View className='item'>
              <View className='top-title'>上次成交时间</View>
              <View className='bottom-total'>18-01-08</View>
            </View>
            <View className='item'>
              <View className='top-title'>上次成交量</View>
              <View className='bottom-total'>5000</View>
            </View>
            <View className='item'>
              <View className='top-title'>总成交量</View>
              <View className='bottom-total'>8000</View>
            </View>
          </View>
        </View>

        {/** 规格选择 */}
        <View className='section standard-section'>
          <View className='header border-bottom_1px'>
            <View className='left-title'>选择规格</View>
            <View className='right' onClick={this.clearSkuQuantity}>
              <View className='right-title'>清空</View>
            </View>
          </View>

          <View className='standard-list'>
            {
              skuList.map((item, index) => {
                return <View className={`standard-item border-bottom_1px ${(item.value > item.sellStock || item.sellStock == 0 )? 'standard-item_less' : ''}`} key={index}>
                  <View className='left'>
                    <View className='title'>{item.skuTitle}</View>
                    <View className='bottom'>
                      <View className='bottom-item'>{SDUtils.formatPrice(`${item.skuPrice}`)}</View>
                      <View className='bottom-item'>库存:{item.sellStock || 0}</View>
                    </View>
                  </View>
                  <View className='right'>
                    <SDQuantity
                      value={item.quantity || 0}
                      // max={item.sellStock || 0}
                      extData={index}
                      onBoundary={this.onQuantityBoundary}
                      onValueChange={this.onQuantityValueChange}
                    />
                  </View>
                </View>
              })
            }
          </View>
          <View className='standard-footer'>
            <View className='item'>
              <View className='title'>数量：</View>
              <View className='item-value'>{totalCount}</View>
            </View>
            <View className='item'>
              <View className='title'>合计：</View>
              <View className='item-value'>{SDUtils.formatPrice(`${totalPrice}`)}</View>
            </View>
          </View>
        </View>

        {/** 详情与评价*/}
        <View className='section detail-section'>
          <View className='detail-header border-bottom_1px'>
            <View className={`detail-bar ${tabBarIndex == 0 ? 'detail-bar_sel' : ''}`} onClick={this.switchTabBar.bind(this, 0)}>
              <View className='content'>
                <View className='title'>详情</View>
                <View className='line'></View>
              </View>
            </View>
            <View className={`detail-bar ${tabBarIndex == 1 ? 'detail-bar_sel' : ''}`} onClick={this.switchTabBar.bind(this, 1)}>
              <View className='content'>
                <View className='title'>评价</View>
                <View className='line'></View>
              </View>
            </View>
          </View>

          <View className='tabbar-content'>
            {
              tabBarIndex == 0 ? <View>
                <Graphics descriptionsMiniList={productData.descriptionsMiniList} />
              </View> : <View>
                <Comment />
              </View>
            }
          </View>
        </View>

        <View style='height: 96rpx;'></View>
        <View className='fixed-bottom border-top_1px' style={`padding-bottom:${bottomSafeHeight}px;`}>
          <View className='bottom-content'>
            <View className='left'>
              <View className='cell-item' onClick={this.gotoCartPage}>
                <Image src={CartIcon} className='cell-icon'/>
                <View className='title'>购物车</View>
                {
                  cartCount > 0 ? (
                    <View className='unread-content'>
                      <View className='unread-title'>{cartCount}</View>
                    </View>
                  ) : null
                }
              </View>
              <View className='cell-item'>
                {
                  isLogin ? <Image src={CollectPreIcon} className='cell-icon'/> : <Image src={CollectNorIcon} className='cell-icon'/>
                }
                <View className='title'>收藏</View>
              </View>
              <Button className='btn-clear cell-item' openType='contact'>
                <Image src={ServiceIcon} className='cell-icon'/>
                <View className='title'>客服</View>
              </Button>
            </View>
            <SDButton sd-class='add-btn' height={96} loading={btnIsLoading} onClick={this.addToCart}>加入购物车</SDButton>
          </View>
        </View>
      </SDBody>
    )
  }

  onSwiperChange = e => {
    let index = e.detail.current
    this.setState({
      bannerIndex: index
    })
  }

  fetchData = async (productId) => {
    let productData: any = {}
    let skuList: any[] = []
    let silverPriceData: any = {}
    let cartCount = 0
    try {
      silverPriceData = await SDUtils.doGet('/wxmini/silverPrice/newest')
      silverPriceData.price = silverPriceData.price || 0

      productData = await SDUtils.doGet(`/wxmini/traderProduct/${productId}`)
      productData.tagsList = (productData.tags || '').split(',').filter(item => item.length > 0)
      productData.processFee = productData.processFee || 0

      let descriptionsMiniList: any[] = []

      let descriptions = (productData.descriptions || []).filter(item => item.type == 'MEDIA')
      for (let i = 0; i < descriptions.length; i++) {
        let item = descriptions[i]
        let itemDescriptionJsonStr = item.description || '{}'
        try {
          let contentList = JSON.parse(itemDescriptionJsonStr)
          descriptionsMiniList.push(...contentList)
        } catch (e) {
          descriptionsMiniList.push({
            content: itemDescriptionJsonStr,
            link: "",
            type: "TEXT"
          })
        }

      }

      productData.descriptionsMiniList = descriptionsMiniList

      skuList = await SDUtils.doGet(`/wxmini/traderProduct/${productId}/spec`)
      skuList.map(item => {
        item.weight = item.weight || 0
        item.quantity = item.quantity || 0
        item.skuPrice = item.weight * (silverPriceData.price + productData.processFee)
        let skuTitle = (item.specItems || []).map(item => item.attrValue).join(' ')
        item.skuTitle = skuTitle
        return item
      })
      let calcSkuList = SDUtils.deepClone(skuList) as any[]
      calcSkuList = calcSkuList.sort((item1, item2) => item1.weight - item2.weight)
      let priceRange = '¥0.00'
      if (calcSkuList.length == 1) {
        priceRange = SDUtils.formatPrice(`${calcSkuList[0].weight * (silverPriceData.price + productData.processFee)}`)
      } else if (calcSkuList.length > 1) {
        let minPrice = SDUtils.formatPrice(`${calcSkuList[0].weight * (silverPriceData.price + productData.processFee)}`)
        let maxPrice = SDUtils.formatPrice(`${calcSkuList[calcSkuList.length - 1].weight * (silverPriceData.price + productData.processFee)}`)
        priceRange = `${minPrice}-${maxPrice}`
      }

      productData.priceRange = priceRange
      // 获取购物车数据
      let cartResp = await SDUtils.doGet('/wxmini/cart')

      let cartItemVos = (cartResp.cartItemVos || [])
      for (let i = 0; i < cartItemVos.length; i++) {
        let item = cartItemVos[i] || {}
        let productVos = item.productVos || []
        for (let j = 0; j < productVos.length; j++) {
          cartCount += productVos[j].quantity
        }
      }
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      this.setState({
        productData: productData,
        skuList: skuList,
        silverPriceData: silverPriceData,
        cartCount: cartCount
      }, () => {
        this.calcPrice()
      })
    }
  }

  calcPrice = () => {
    let totalCount = 0
    let totalPrice = 0
    const { skuList, silverPriceData, productData } = this.state
    for (let i = 0; i < skuList.length; i++) {
      let skuItem = skuList[i]
      if (!skuItem.quantity || skuItem.quantity <= 0) {
        continue
      }
      totalCount += skuItem.quantity
      totalPrice += (skuItem.quantity) * ((silverPriceData.price || 0) + (productData.processFee || 0)) * skuItem.weight
    }


    this.setState({
      mainIsLoading: false,
      totalCount: totalCount,
      totalPrice: totalPrice
    })
  }

  gotoVideoPlayer = (_) => {
    console.log('进入视频播放界面')
  }

  previewImage = (currentImg: string) => {
    const { productData = {} } = this.state
    let productMedias = productData.productMedias || []
    let imgList = productMedias.map(item => item.mediaUrl)
    Taro.previewImage({
      urls: imgList,
      current: currentImg
    })
  }

  onQuantityBoundary = (_: string, type: 'minus' | 'plus') => {
    if (type == 'plus') {
      SDUtils.showMsg('库存不足')
    } else {
      SDUtils.showMsg('数量不能少于0')
    }
  }

  onQuantityValueChange = (value: string, extData) => {
    let { skuList = [] } = this.state
    let quantity = parseInt(value)
    quantity = isNaN(quantity) ? 0 : quantity
    skuList[extData].quantity = quantity
    this.setState({
      skuList: skuList
    }, () => {
      this.calcPrice()
    })
  }

  clearSkuQuantity = () => {
    let { skuList = [] } = this.state
    skuList = skuList.map(item => {
      item.quantity = 0
      return item
    })
    this.setState({
      skuList: skuList
    }, () => {
      this.calcPrice()
    })
  }

  switchTabBar = (index: number) => {
    this.setState({
      tabBarIndex: index
    })
  }

  gotoCartPage = () => {
    Taro.switchTab({
      url: '/pages/tabbar/cart/index'
    })
  }

  addToCart = () => {
    const { btnIsLoading, skuList } = this.state
    if (btnIsLoading) { return }
    if (skuList.length <= 0) {
      return
    }
    this.setState({
      btnIsLoading: true
    },async () => {
      let paramList: any[] = []
      for (let i = 0; i < skuList.length; i++) {
        let item = skuList[i]
        paramList.push({
          skuId: item.skuId,
          quantity: item.quantity
        })
      }
      let cartCount = 0
      try {
        await SDUtils.doPut('/wxmini/cart/batch', paramList)
        const cartResp = await SDUtils.doGet('/wxmini/cart')
        this.props.setShopCart({
          cartList: cartResp.cartItemVos || [],
          invalidCartList: []
        })
        let cartItemVos = (cartResp.cartItemVos || [])
        for (let i = 0; i < cartItemVos.length; i++) {
          let item = cartItemVos[i] || {}
          let productVos = item.productVos || []
          for (let j = 0; j < productVos.length; j++) {
            cartCount += productVos[j].quantity
          }
        }
        SDUtils.showMsg('已成功加入购物车')
      } catch (e) {
        SDUtils.showMsg(e)
      } finally {
        this.setState({
          btnIsLoading: false,
          cartCount: cartCount
        })
      }
    })

  }
}

export default GoodsDetailPage as ComponentClass<PageOwnProps, PageState>
